from django import template
from django.template import Library, Node, TemplateSyntaxError, Context, loader
from django.shortcuts import render_to_response
 
register = Library()
 
class Articles(template.Node):
 
  def __init__(self, category_name='name', articles_list_key='articles'):
    self.articles_list_key = articles_list_key
    self.category_name = category_name
 
  def render(self, context):
    """render a category of articles for an iterable list of articles"""
    (Story, Cat) = self.articles_list_key.split(".")
    if context.has_key(Story) and context[Story].has_key(Cat):
      articles_list = context[Story][Cat]
      t = loader.get_template('articles.html')
      c = Context({'articles': articles_list, 'name': self.category_name})
      return t.render(c)
    else:
      TemplateSyntaxError('%s is not defined in the context' % self.articles_list_key)
 
def articles(parser, token):
  args = token.contents.split()
  if len(args) > 2:
    return Articles(args[1], args[2])
  else:
    return Articles()
 
register.tag('garticles', articles)
